شماره مستند: ARCH-MCP-1405-001
نسخه: ۱.۰
تاریخ تهیه: آبان ۱۴۰۵
طبقه‌بندی: فنی-داخلی
TECHNICAL DESIGN DOCUMENT

ثبت XAiMcpServer به‌عنوان Entity و مدیریت داینامیک

Seed از appSettings + CRUD API + یکپارچه‌سازی با XMcpServerConnectionManager

هدف مستند:
این مستند، مراحل دقیق و گام‌به‌گام ثبت سرورهای MCP به‌عنوان یک Entity کامل در ماژول xAiModels، همراه با لایه‌های Repository/Service/Enricher، Seeder خودکار از appSettings، کنترلرهای CRUD، و اتصال به XMcpServerConnectionManager را شرح می‌دهد. تمام الگوها دقیقاً منطبق بر کدهای موجود پروژه (مانند XAiProject و XAiConversation) پیاده‌سازی می‌شوند.
۰

نمای کلی معماری و جریان داده

Architecture Overview

جریان کلی سیستم به این شکل خواهد بود:

┌─────────────────────────────────────────────────────────────────┐
│  appsettings.json → "McpServers:Servers[]"                      │
│         │                                                        │
│         ▼                                                        │
│  XMcpServerSeederService (IHostedService)                       │
│         │   (در Startup اجرا می‌شود)                              │
│         ▼                                                        │
│  IXAiMcpServerRepositoryService → AddAsync/UpdateAsync           │
│         │                                                        │
│         ▼                                                        │
│  [AiMcpServers] Table (SQL/Mongo/InMemory)                      │
│         │                                                        │
│         ├──→ McpServersController (CRUD API)                    │
│         │         │                                              │
│         │         ▼                                              │
│         │    XMcpServerConnectionManager.RefreshAsync()          │
│         │                                                        │
│         ▼                                                        │
│  XMcpServerConnectionManager                                    │
│         │   (Ping + ListTools + Cache)                          │
│         ▼                                                        │
│  ChatOptions.Tools → IXDefaultAiService                         │
└─────────────────────────────────────────────────────────────────┘
💡 نکته کلیدی: appSettings فقط نقش Seed اولیه را دارد. پس از آن، مدیریت کامل از طریق API و دیتابیس انجام می‌شود. اگر سرور جدیدی به appSettings اضافه شود، Seeder در استارتاپ بعدی آن را ایجاد می‌کند و اگر UpdateExisting = true باشد، موجودیت‌های قبلی را هم به‌روزرسانی می‌کند.

ساختار فایل‌های جدید/تغییر یافته:

xSaherelmWorkspace/ ├── Modules/xAiModels/ │ ├── Models/ │ │ ├── Entities/ │ │ │ └── XAiMcpServer.cs [NEW] │ │ │ ├── Dtos/ │ │ │ │ └── XAiMcpServerDto.cs [NEW] │ │ │ └── XMcpServerDescriptor.cs [NEW] │ │ ├── Configurations/ │ │ │ ├── XAiModelMappersProfile.cs [MODIFY] │ │ │ └── Entities/ │ │ │ └── XAiMcpServerEntityConfiguration.cs [NEW] │ │ ├── Constants/XAiModelsConstants.cs [MODIFY] │ │ ├── Interfaces/ │ │ │ ├── Entities/ │ │ │ │ ├── IXAiMcpServerKeyGenerator.cs │ │ │ │ ├── IXAiMcpServerRepository.cs │ │ │ │ ├── IXAiMcpServerRepositoryEvents.cs │ │ │ │ ├── IXAiMcpServerRepositoryProvider.cs │ │ │ │ └── IXAiMcpServerEntityHub.cs │ │ │ ├── Dtos/ │ │ │ │ ├── IXAiMcpServerDtoHub.cs │ │ │ │ ├── IXAiMcpServerRepositoryService.cs │ │ │ │ └── IXAiMcpServerServiceProvider.cs │ │ │ └── Enrichers/ │ │ │ └── IXAiMcpServerEnricher.cs │ │ ├── Providers/ │ │ │ ├── Entities/ │ │ │ │ ├── XAiMcpServerEFRepository.cs │ │ │ │ ├── XAiMcpServerInMemoryRepository.cs │ │ │ │ ├── XAiMcpServerMongoRepository.cs │ │ │ │ ├── XAiMcpServerKeyGenerator.cs │ │ │ │ ├── XAiMcpServerRepositoryEvents.cs │ │ │ │ ├── XAiMcpServerEntityHub.cs │ │ │ │ ├── XAiMcpServerRepositoryProvider.cs │ │ │ │ └── XAiMcpServerSeederBase.cs │ │ │ ├── Dtos/ │ │ │ │ ├── XAiMcpServerDtoHub.cs │ │ │ │ ├── XAiMcpServerRepositoryService.cs │ │ │ │ └── XAiMcpServerServiceProvider.cs │ │ │ ├── Enrichers/ │ │ │ │ └── XAiMcpServerEnricher.cs │ │ │ └── XAiMcpServerEntityRegisterar.cs │ │ ├── Helpers/XAiModelsHelper.cs [MODIFY] │ │ └── DI/XDIHelperExtension.cs [MODIFY] │ │ ├── xAiApi/ │ ├── Configurations/ │ │ └── XMcpServersConfiguration.cs [NEW] │ ├── Services/ │ │ ├── XMcpServerSeederService.cs [NEW] │ │ └── XMcpServerConnectionManager.cs [MODIFY] │ ├── Controllers/ │ │ └── McpServersController.cs [NEW] │ ├── Database/XAiApiDbContext.cs [MODIFY] │ ├── Startup.cs [MODIFY] │ └── appsettings.json [MODIFY]
۱

تعریف Entity در xAiModels

Entity Layer / Models/Entities/XAiMcpServer.cs

ابتدا موجودیت اصلی را با الگوبرداری دقیق از XAiProject و XAiVector تعریف می‌کنیم. فیلدهای JSON (مانند Arguments، Headers، EnvironmentVariables) به‌صورت رشته ذخیره می‌شوند تا در هر سه Repository (EF/Mongo/InMemory) قابل نگهداری باشند.

xAiModels/Models/Entities/XAiMcpServer.cs
using System;
using xModels.Base;
using System.ComponentModel.DataAnnotations;

namespace xAiModels.Models.Entities
{
    /// <summary>
    /// سرور MCP ثبت‌شده در دیتابیس (قابل مدیریت از طریق API) ...
    /// </summary>
    public class XAiMcpServer : XBaseGuidIDEntity
    {
        /// <summary>
        /// شناسه مالک (کاربری که این سرور را ثبت کرده) ...
        /// </summary>
        [Required]
        [StringLength(255)]
        public string OwnerId { get; set; }

        /// <summary>
        /// نام یکتای سرور (برای هر Owner) ...
        /// </summary>
        [Required]
        [StringLength(255)]
        public string Name { get; set; }

        /// <summary>
        /// توضیحات ...
        /// </summary>
        [StringLength(1000)]
        public string Description { get; set; }

        /// <summary>
        /// فعال/غیرفعال ...
        /// </summary>
        public bool Enabled { get; set; } = true;

        /// <summary>
        /// نوع Transport: "stdio" یا "http" ...
        /// </summary>
        [Required]
        [StringLength(50)]
        public string Transport { get; set; } = "stdio";

        // --- تنظیمات Stdio ---
        [StringLength(500)]
        public string Command { get; set; }

        /// <summary>
        /// آرگومان‌ها به‌صورت JSON Array (مثلاً ["xAiMcpServer.dll"]) ...
        /// </summary>
        public string Arguments { get; set; }

        [StringLength(1000)]
        public string WorkingDirectory { get; set; }

        /// <summary>
        /// متغیرهای محیطی به‌صورت JSON Object ...
        /// </summary>
        public string EnvironmentVariables { get; set; }

        // --- تنظیمات HTTP ---
        [StringLength(1000)]
        public string Endpoint { get; set; }

        /// <summary>
        /// هدرهای HTTP به‌صورت JSON Object ...
        /// </summary>
        public string Headers { get; set; }

        /// <summary>
        /// مهلت اتصال و اعتبارسنجی (ثانیه) ...
        /// </summary>
        public int TimeoutSeconds { get; set; } = 30;

        // --- Audit ---
        public DateTime CreatedOn { get; set; }
        public DateTime UpdatedAt { get; set; }
    }
}
xAiModels/Models/Dtos/XAiMcpServerDto.cs
using System;
using xModels.Base;
using xModels.Dtos;

namespace xAiModels.Models.Dtos
{
    public class XAiMcpServerDto : XBaseGuidIDEntityDto
    {
        public string OwnerId { get; set; }
        public virtual XPersonDto Owner { get; set; } = null;

        public string Name { get; set; }
        public string Description { get; set; }
        public bool Enabled { get; set; }
        public string Transport { get; set; }

        public string Command { get; set; }
        public string Arguments { get; set; }
        public string WorkingDirectory { get; set; }
        public string EnvironmentVariables { get; set; }

        public string Endpoint { get; set; }
        public string Headers { get; set; }

        public int TimeoutSeconds { get; set; }

        public DateTime CreatedOn { get; set; }
        public DateTime UpdatedAt { get; set; }
    }
}
xAiModels/Models/XMcpServerDescriptor.cs
using System.Collections.Generic;

namespace xAiModels.Models
{
    /// <summary>
    /// Descriptor سرور MCP که مستقیماً از appSettings خوانده می‌شود
    /// و سپس توسط Seeder به یک XAiMcpServer Entity تبدیل می‌گردد ...
    /// </summary>
    public class XMcpServerDescriptor
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public bool Enabled { get; set; } = true;
        public string Transport { get; set; } = "stdio";
        public int TimeoutSeconds { get; set; } = 30;

        // Stdio
        public string Command { get; set; }
        public List<string> Arguments { get; set; } = new();
        public string WorkingDirectory { get; set; }
        public Dictionary<string, string> EnvironmentVariables { get; set; }

        // HTTP
        public string Endpoint { get; set; }
        public Dictionary<string, string> Headers { get; set; }
    }
}
۲

ثابت‌ها و Configuration

Constants / EntityConfiguration

ثابت‌های جدید را به XAiModelsConstants اضافه کنید (دقیقاً مطابق الگوی موجود):

xAiModels/Constants/XAiModelsConstants.cs (MODIFY)
// ── اضافه کنید در struct XAiModelsConstants ──

// Table Mapping
public const string XAiMcpServerTable = "AiMcpServers";

// GraphQL Collection Mappings
public const string XAiMcpServerSingleName = "aiMcpServer";
public const string XAiMcpServerCollectionName = "aiMcpServers";

// Hubs
public const string XAiMcpServerDtoHub = "aiMcpServerDto";
public const string XAiMcpServerEntityHub = "aiMcpServerEntity";

// EF Repositories Helper Extensions
public const string GetXAiMcpServerEFRepositoryDescriptor = "GetXAiMcpServerEFRepositoryDescriptor";
xAiModels/Configurations/Entities/XAiMcpServerEntityConfiguration.cs
using System;
using xAiModels.Constants;
using xDataService.Providers;
using xAiModels.Models.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace xAiModels.Configurations.Entities
{
    public class XAiMcpServerEntityConfiguration : XBaseEntityTypeConfiguration<XAiMcpServer, Guid>
    {
        public override void Configure(EntityTypeBuilder<XAiMcpServer> builder)
        {
            builder.ToTable(XAiModelsConstants.XAiMcpServerTable);

            // نام برای هر Owner یکتاست
            builder.HasIndex(x => new { x.OwnerId, x.Name }).IsUnique();
        }
    }
}
xAiModels/Providers/XAiMcpServerEntityRegisterar.cs
using System;
using xDataService.Providers;
using xDataService.Interfaces;
using xAiModels.Models.Entities;
using Microsoft.EntityFrameworkCore;
using xAiModels.Configurations.Entities;

namespace xAiModels.Providers
{
    public class XAiMcpServerEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar
    {
        public XAiMcpServerEntityRegisterar()
        : base(nameof(XAiMcpServerEntityRegisterar))
        {
            AddEntity<XAiMcpServer, Guid>();
        }

        public override void ConfigureEntities(ModelBuilder modelBuilder)
        {
            modelBuilder
                .ApplyConfigurationsFromAssembly(typeof(XAiMcpServerEntityConfiguration).Assembly);

            base.ConfigureEntities(modelBuilder);
        }
    }
}
۳

لایه Interfaces

Interfaces / Entities + Dtos + Enrichers

مطابق الگوی XAiProject، تمام اینترفیس‌های مربوطه را در سه پوشه Entities، Dtos و Enrichers ایجاد کنید:

الف) Interfaces/Entities

xAiModels/Interfaces/Entities/IXAiMcpServerKeyGenerator.cs
using System;
using xDataService.Interfaces;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Entities
{
    public interface IXAiMcpServerKeyGenerator : IXKeyGenerator<XAiMcpServer, Guid> { }
}
xAiModels/Interfaces/Entities/IXAiMcpServerRepository.cs
using System;
using xDataService.Interfaces;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Entities
{
    public interface IXAiMcpServerRepository : IXBaseRepository<XAiMcpServer, Guid> { }
}
xAiModels/Interfaces/Entities/IXAiMcpServerRepositoryEvents.cs
using xDataService.Interfaces;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Entities
{
    public interface IXAiMcpServerRepositoryEvents : IXBaseRepositoryEvents<XAiMcpServer> { }
}
xAiModels/Interfaces/Entities/IXAiMcpServerEntityHub.cs
using System;
using xPushService.Interfaces;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Entities
{
    public interface IXAiMcpServerEntityHub : IXBaseEntityHub<XAiMcpServer, Guid> { }
}
xAiModels/Interfaces/Entities/IXAiMcpServerRepositoryProvider.cs
using System;
using xPushService.Interfaces;
using xAiModels.Models.Entities;
using xAiModels.Providers.Entities;

namespace xAiModels.Interfaces.Entities
{
    public interface IXAiMcpServerRepositoryProvider
        : IXBaseEntityProvider<XAiMcpServer, Guid, XAiMcpServerEntityHub> { }
}

ب) Interfaces/Dtos

xAiModels/Interfaces/Dtos/IXAiMcpServerDtoHub.cs
using System;
using xAiModels.Models.Dtos;
using xPushService.Interfaces;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Dtos
{
    public interface IXAiMcpServerDtoHub
        : IXBaseDtoHub<XAiMcpServer, XAiMcpServerDto, Guid> { }
}
xAiModels/Interfaces/Dtos/IXAiMcpServerRepositoryService.cs
using System;
using System.Threading;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xDataService.Interfaces;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Dtos
{
    public interface IXAiMcpServerRepositoryService
        : IXBaseRepositoryService<XAiMcpServer, XAiMcpServerDto, Guid>
    {
        /// <summary>
        /// یافتن سرور بر اساس OwnerId و Name ...
        /// </summary>
        Task<XAiMcpServerDto> FindByNameAsync(
            string ownerId,
            string name,
            CancellationToken cancellationToken = default
        );
    }
}
xAiModels/Interfaces/Dtos/IXAiMcpServerServiceProvider.cs
using System;
using xAiModels.Models.Dtos;
using xPushService.Interfaces;
using xAiModels.Providers.Dtos;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Dtos
{
    public interface IXAiMcpServerServiceProvider
        : IXBaseDtoProvider<XAiMcpServer, XAiMcpServerDto, Guid, XAiMcpServerDtoHub> { }
}

ج) Interfaces/Enrichers

xAiModels/Interfaces/Enrichers/IXAiMcpServerEnricher.cs
using System.Threading;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xAiModels.Models.Entities;
using System.Collections.Generic;

namespace xAiModels.Interfaces.Enrichers
{
    public interface IXAiMcpServerEnricher
    {
        Task<XAiMcpServerDto> Enrich(
            XAiMcpServer source,
            CancellationToken cancellationToken = default
        );

        Task<XAiMcpServerDto> Enrich(
            XAiMcpServerDto source,
            CancellationToken cancellationToken = default
        );

        Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
            IEnumerable<XAiMcpServer> sources,
            CancellationToken cancellationToken = default
        );

        Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
            IEnumerable<XAiMcpServerDto> sources,
            CancellationToken cancellationToken = default
        );
    }
}
۴

لایه Repository

EF / Mongo / InMemory + KeyGenerator + Events + Hubs

سه نوع Repository و اجزای جانبی آن‌ها را دقیقاً مطابق با XAiProjectEFRepository و XAiProjectMongoRepository بسازید:

xAiModels/Providers/Entities/XAiMcpServerEFRepository.cs
using System;
using xDataService.Db;
using xDataService.Providers;
using xDataService.Interfaces;
using xAiModels.Models.Entities;
using xDataService.Configuration;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerEFRepository<TContext>
        : XBaseEFRepository<XAiMcpServer, Guid, TContext>, IXAiMcpServerRepository
        where TContext : XDbContext
    {
        public XAiMcpServerEFRepository(
            IXUnitOfWorks<TContext> unitOfWorks,
            XDataServiceConfiguration configuration,
            IXAiMcpServerKeyGenerator keyGenerator = null,
            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
        ) : base(unitOfWorks, configuration, keyGenerator, baseRepositoryEvents) { }
    }
}
xAiModels/Providers/Entities/XAiMcpServerMongoRepository.cs
using System;
using xDataService.Providers;
using xAiModels.Models.Entities;
using xDataService.Configuration;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerMongoRepository
        : XBaseMongoRepository<XAiMcpServer, Guid>, IXAiMcpServerRepository
    {
        public XAiMcpServerMongoRepository(
            XDataBaseConfiguration dbConfiguration,
            XDataServiceConfiguration configuration,
            string collectionName = null,
            IXAiMcpServerKeyGenerator keyGenerator = null,
            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
        ) : base(dbConfiguration, configuration, collectionName, keyGenerator, baseRepositoryEvents) { }
    }
}
xAiModels/Providers/Entities/XAiMcpServerInMemoryRepository.cs
using System;
using xDataService.Providers;
using xAiModels.Models.Entities;
using xDataService.Configuration;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerInMemoryRepository
        : XBaseInMemoryRepository<XAiMcpServer, Guid>, IXAiMcpServerRepository
    {
        public XAiMcpServerInMemoryRepository(
            XDataServiceConfiguration configuration,
            IXAiMcpServerKeyGenerator keyGenerator = null,
            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
        ) : base(configuration, keyGenerator, baseRepositoryEvents) { }
    }
}
xAiModels/Providers/Entities/XAiMcpServerKeyGenerator.cs
using xDataService.Providers;
using xAiModels.Models.Entities;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerKeyGenerator
        : XGuidKeyGenerator<XAiMcpServer>, IXAiMcpServerKeyGenerator { }
}
xAiModels/Providers/Entities/XAiMcpServerRepositoryEvents.cs
using xDataService.Providers;
using xAiModels.Models.Entities;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerRepositoryEvents
        : XBaseRepositoryEvents<XAiMcpServer>, IXAiMcpServerRepositoryEvents { }
}
xAiModels/Providers/Entities/XAiMcpServerEntityHub.cs
using System;
using xPushService.Base;
using xAiModels.Models.Entities;
using Microsoft.Extensions.Logging;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerEntityHub
        : XBaseEntityHub<XAiMcpServer, Guid>, IXAiMcpServerEntityHub
    {
        public XAiMcpServerEntityHub(ILogger<XAiMcpServerEntityHub> logger)
            : base(logger) { }
    }
}
xAiModels/Providers/Entities/XAiMcpServerRepositoryProvider.cs
using System;
using xPushService.Base;
using xAiModels.Models.Entities;
using xDataService.Configuration;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.SignalR;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerRepositoryProvider
        : XBaseEntityProvider<XAiMcpServer, Guid, XAiMcpServerEntityHub>, IXAiMcpServerRepositoryProvider
    {
        public XAiMcpServerRepositoryProvider(
            IHubContext<XAiMcpServerEntityHub> hub,
            IXAiMcpServerRepository repository,
            XDataServiceConfiguration dataConfiguration,
            IXIdentityProvider identityProvider = null
        ) : base(hub, repository, dataConfiguration, identityProvider) { }
    }
}
۵

لایه Service (RepositoryService + ServiceProvider + Enricher)

Providers/Dtos + Enrichers
xAiModels/Configurations/XAiModelMappersProfile.cs (MODIFY)
// ── درون سازنده XAiModelMappersProfile اضافه کنید ──

// XAiMcpServer
CreateMap<XAiMcpServer, XAiMcpServerDto>();
CreateMap<XAiMcpServerDto, XAiMcpServer>();
xAiModels/Providers/Enrichers/XAiMcpServerEnricher.cs
using System.Linq;
using xModels.Dtos;
using System.Threading;
using xCommons.Extensions;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xAiModels.Models.Entities;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using xIdentityService.Extensions;
using xAiModels.Interfaces.Enrichers;

namespace xAiModels.Providers.Enrichers
{
    public class XAiMcpServerEnricher : IXAiMcpServerEnricher
    {
        private readonly IXIdentityProvider identityProvider;

        public XAiMcpServerEnricher(IXIdentityProvider identityProvider)
        {
            this.identityProvider = identityProvider;
        }

        public virtual async Task<XAiMcpServerDto> Enrich(
            XAiMcpServer source,
            CancellationToken cancellationToken = default
        )
        {
            var result = source.MapConvert<XAiMcpServerDto, XAiMcpServer>();
            result = await Enrich(source: result, cancellationToken: cancellationToken);
            return result;
        }

        public virtual async Task<XAiMcpServerDto> Enrich(
            XAiMcpServerDto source,
            CancellationToken cancellationToken = default
        )
        {
            XPersonDto owner = null;
            if (!source.OwnerId.IsNullOrEmpty())
            {
                var device = identityProvider.GetDevice();
                var userInfo = await identityProvider.GetUserInfo(
                    device: device,
                    userSelectByParam: source.OwnerId
                );
                owner = userInfo.ToXPersonDto();
            }

            var result = source.MapConvert<XAiMcpServerDto, XAiMcpServerDto>();
            result.Owner = owner;
            return result;
        }

        public virtual async Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
            IEnumerable<XAiMcpServer> sources,
            CancellationToken cancellationToken = default
        )
        {
            var tasks = sources.Select(x => Enrich(x, cancellationToken));
            return await Task.WhenAll(tasks);
        }

        public virtual async Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
            IEnumerable<XAiMcpServerDto> sources,
            CancellationToken cancellationToken = default
        )
        {
            var tasks = sources.Select(x => Enrich(x, cancellationToken));
            return await Task.WhenAll(tasks);
        }
    }
}
xAiModels/Providers/Dtos/XAiMcpServerRepositoryService.cs
using System;
using System.Linq;
using System.Threading;
using xCommons.Extensions;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xDataService.Providers;
using xAiModels.Configurations;
using xAiModels.Interfaces.Dtos;
using xAiModels.Interfaces.Entities;
using xAiModels.Interfaces.Enrichers;

namespace xAiModels.Providers.Dtos
{
    public class XAiMcpServerRepositoryService
        : XBaseRepositoryService<XAiMcpServer, XAiMcpServerDto, Guid>, IXAiMcpServerRepositoryService
    {
        private readonly IXAiMcpServerEnricher enricher;
        private readonly IXAiMcpServerRepository repository;

        public XAiMcpServerRepositoryService(
            IXAiMcpServerRepository repository,
            IXAiMcpServerEnricher enricher
        ) : base(repository, mapperProfiles: [new XAiModelMappersProfile()])
        {
            this.enricher = enricher;
            this.repository = repository;
        }

        /// <summary>
        /// یافتن سرور بر اساس OwnerId و Name ...
        /// </summary>
        public virtual async Task<XAiMcpServerDto> FindByNameAsync(
            string ownerId,
            string name,
            CancellationToken cancellationToken = default
        )
        {
            // اعتبارسنجی ورودی‌ها
            if (ownerId.IsNullOrEmpty() || name.IsNullOrEmpty())
                return null;

            // جستجو در Repository
            var entity = await repository.FindOneAsync(
                includeBuilder: null,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken,
                predicate: x => x.OwnerId == ownerId && x.Name == name
            );

            // عدم یافتن → null
            if (entity.IsNullOrDefault())
                return null;

            // Enrich و بازگشت
            return await enricher.Enrich(source: entity, cancellationToken: cancellationToken);
        }
    }
}
xAiModels/Providers/Dtos/XAiMcpServerDtoHub.cs
using System;
using xPushService.Base;
using xAiModels.Models.Dtos;
using xAiModels.Interfaces.Dtos;
using xAiModels.Models.Entities;
using Microsoft.Extensions.Logging;

namespace xAiModels.Providers.Dtos
{
    public class XAiMcpServerDtoHub
        : XBaseDtoHub<XAiMcpServer, XAiMcpServerDto, Guid>, IXAiMcpServerDtoHub
    {
        public XAiMcpServerDtoHub(ILogger<XAiMcpServerDtoHub> logger)
            : base(logger) { }
    }
}
xAiModels/Providers/Dtos/XAiMcpServerServiceProvider.cs
using System;
using xPushService.Base;
using xAiModels.Models.Dtos;
using xAiModels.Interfaces.Dtos;
using xAiModels.Models.Entities;
using xDataService.Configuration;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.SignalR;

namespace xAiModels.Providers.Dtos
{
    public class XAiMcpServerServiceProvider
        : XBaseDtoProvider<XAiMcpServer, XAiMcpServerDto, Guid, XAiMcpServerDtoHub>, IXAiMcpServerServiceProvider
    {
        public XAiMcpServerServiceProvider(
            IHubContext<XAiMcpServerDtoHub> hub,
            XDataServiceConfiguration dataConfiguration,
            IXAiMcpServerRepositoryService service,
            IXIdentityProvider identityProvider = null
        ) : base(hub, dataConfiguration, service, identityProvider) { }
    }
}
۶

Helper و ثبت در DI

XAiModelsHelper + XDIHelperExtension

مطابق الگوی موجود در XAiModelsHelper، سه متد برای ساخت Repository Descriptor اضافه کنید:

xAiModels/Helpers/XAiModelsHelper.cs (MODIFY)
// ── درون کلاس XAiModelsHelper اضافه کنید ──

#region XAiMcpServer ...
// EF Repository Descriptor
public static XEFRepositoryDescriptor<
    XAiMcpServer, Guid,
    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
    XAiMcpServerGraphType, GuidGraphType,
    XAiMcpServerGraphQuery,
    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
    XAiMcpServerGraphSchema,
    IXAiMcpServerRepository,
    XAiMcpServerEFRepository<TContext>, TContext
> GetXAiMcpServerEFRepositoryDescriptor<TContext>()
where TContext : XDbContext
{
    return new XEFRepositoryDescriptor<...>();  // پر کردن کامل نوع‌ها
}

// Mongo Repository Descriptor
public static XMongoRepositoryDescriptor<
    XAiMcpServer, Guid,
    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
    XAiMcpServerGraphType, GuidGraphType,
    XAiMcpServerGraphQuery,
    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
    XAiMcpServerGraphSchema,
    IXAiMcpServerRepository, XAiMcpServerMongoRepository
> GetXAiMcpServerMongoRepositoryDescriptor()
{
    return new XMongoRepositoryDescriptor<...>();
}

// InMemory Repository Descriptor
public static XInMemoryRepositoryDescriptor<
    XAiMcpServer, Guid,
    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
    XAiMcpServerGraphType, GuidGraphType,
    XAiMcpServerGraphQuery,
    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
    XAiMcpServerGraphSchema,
    IXAiMcpServerRepository, XAiMcpServerInMemoryRepository
> GetXAiMcpServerInMemoryRepositoryDescriptor()
{
    return new XInMemoryRepositoryDescriptor<...>();
}
#endregion
⚠️ توجه: برای سادگی، GraphQL types (مانند XAiMcpServerGraphType، XAiMcpServerGraphQuery و...) در این مستند اورده نشده‌اند. اگر پروژه شما از GraphQL استفاده نمی‌کند، می‌توانید این پارامترها را با null جایگزین کنید یا با الگوگیری دقیق از XAiProjectGraphType و... آن‌ها را ایجاد نمایید.

سپس در XDIHelperExtension پروژه xAiModels، ثبت‌ها را اضافه کنید:

xAiModels/DI/XDIHelperExtension.cs (MODIFY)
// ── ۱) متغیر استاتیک جدید اضافه کنید ──
private static XRepositoryDescriptor aiMcpServerDescriptor = null;

// ── ۲) درون switch روی repositoryType، در بخش EF ──
aiMcpServerDescriptor = typeof(XAiModelsHelper)
    .InvokeGenericMethod<XRepositoryDescriptor>(
        args: null,
        runtimeType: contextType,
        methodName: XAiModelsConstants.GetXAiMcpServerEFRepositoryDescriptor
    );

// ── ۳) درون switch، در بخش Mongo ──
aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerMongoRepositoryDescriptor();

// ── ۴) درون switch، در بخش InMemory ──
aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerInMemoryRepositoryDescriptor();

// ── ۵) درون region Register Repository Descriptor ──
if (!aiMcpServerDescriptor.IsNull())
{
    services.AddXRepository(lifeTime: lifeTime, descriptor: aiMcpServerDescriptor);
}

// ── ۶) درون region Register Services، یک region جدید اضافه کنید ──
#region AiMcpServer ...
services.Add(
    new ServiceDescriptor(typeof(IXAiMcpServerServiceProvider),
                          typeof(XAiMcpServerServiceProvider), lifeTime)
);
services.Add(
    new ServiceDescriptor(typeof(IXAiMcpServerRepositoryService),
                          typeof(XAiMcpServerRepositoryService), lifeTime)
);
services.Add(
    new ServiceDescriptor(typeof(IXAiMcpServerRepositoryProvider),
                          typeof(XAiMcpServerRepositoryProvider), lifeTime)
);
services.Add(
    new ServiceDescriptor(typeof(IXAiMcpServerEnricher),
                          typeof(XAiMcpServerEnricher), lifeTime)
);
#endregion

همچنین در UseXAiDataService (همان فایل، برای Hubs):

// ── اضافه کنید ──
pushHelper.AddHub<XAiMcpServerDtoHub>(XAiModelsConstants.XAiMcpServerDtoHub);
pushHelper.AddHub<XAiMcpServerEntityHub>(XAiModelsConstants.XAiMcpServerEntityHub);

// در بخش Use Repository Descriptor
if (!aiMcpServerDescriptor.IsNull())
{
    app.UseXRepository(descriptor: aiMcpServerDescriptor,
                       isDevelopmentEnvironment: isDevelopmentEnvironment);
}
۷

ثبت Registerar در DbContext

XAiApiDbContext.cs (MODIFY)

در فایل XAiApiDbContext.cs، نام Registerar جدید را به لیست dynamicEntityRegisterarsNames اضافه کنید:

xAiApi/Database/XAiApiDbContext.cs (MODIFY)
dynamicEntityRegisterarsNames: [
    nameof(XTagEntityRegisterar),
    nameof(XFileEntityRegisterar),
    nameof(XStringEntityRegisterar),
    nameof(XAiMessageEntityRegisterar),
    nameof(XAiProjectEntityRegisterar),
    nameof(XAiConversationEntityRegisterar),
    nameof(XAiMcpServerEntityRegisterar),    // ← جدید
]
💡 نکته: پس از این تغییر، یک Migration جدید برای جدول AiMcpServers بسازید:

dotnet ef migrations add AddAiMcpServersTable --project xAiApi --context XAiApiDbContext

سپس dotnet ef database update.
۸

Seeder از appSettings

XMcpServersConfiguration + XMcpServerSeederService

این بخش هسته اصلی درخواست شماست: خواندن McpServers از appSettings، تبدیل به Entity، و ذخیره در DB. این عملیات به‌صورت IHostedService در استارتاپ اجرا می‌شود.

الف) مدل Configuration

xAiApi/Configurations/XMcpServersConfiguration.cs
using System.Collections.Generic;
using xAiModels.Models;

namespace xAiApi.Configurations
{
    /// <summary>
    /// Configuration مربوط به McpServers که از appSettings خوانده می‌شود ...
    /// </summary>
    public class XMcpServersConfiguration
    {
        /// <summary>
        /// آیا Seeder در استارتاپ اجرا شود؟
        /// </summary>
        public bool SyncOnStartup { get; set; } = true;

        /// <summary>
        /// آیا اگر سروری از قبل وجود دارد، فیلدهایش به‌روزرسانی شود؟
        /// </summary>
        public bool UpdateExisting { get; set; } = false;

        /// <summary>
        /// OwnerId پیش‌فرض برای سرورهای Seed شده ...
        /// (اگر خالی باشد از "system" استفاده می‌شود)
        /// </summary>
        public string DefaultOwnerId { get; set; } = "system";

        /// <summary>
        /// لیست سرورهای MCP ...
        /// </summary>
        public List<XMcpServerDescriptor> Servers { get; set; } = new();
    }
}

ب) سرویس Seeder

xAiApi/Services/XMcpServerSeederService.cs
using System;
using System.Linq;
using System.Text.Json;
using xAiModels.Models;
using System.Threading;
using System.Threading.Tasks;
using xCommons.Extensions;
using xAiModels.Models.Dtos;
using System.Collections.Generic;
using Microsoft.Extensions.Hosting;
using xAiApi.Configurations;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using xAiModels.Interfaces.Dtos;

namespace xAiApi.Services
{
    /// <summary>
    /// سرویس پس‌زمینه‌ای که در استارتاپ، سرورهای MCP را از appSettings
    /// می‌خواند و در دیتابیس ایجاد/به‌روزرسانی می‌کند ...
    /// </summary>
    public class XMcpServerSeederService : IHostedService
    {
        private readonly ILogger<XMcpServerSeederService> logger;
        private readonly XMcpServersConfiguration config;
        private readonly IXAiMcpServerRepositoryService repositoryService;

        public XMcpServerSeederService(
            ILogger<XMcpServerSeederService> logger,
            IOptions<XMcpServersConfiguration> config,
            IXAiMcpServerRepositoryService repositoryService
        )
        {
            this.logger = logger;
            this.config = config.Value;
            this.repositoryService = repositoryService;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            // اگر Sync غیرفعال است، هیچ کاری نکن
            if (!config.SyncOnStartup)
            {
                logger.LogInformation(
                    "MCP Seed: SyncOnStartup=false، عملیات Seed اجرا نشد.");
                return;
            }

            // اگر لیست خالی است، خارج شو
            if (!config.Servers.HasChild())
            {
                logger.LogInformation(
                    "MCP Seed: هیچ سروری در appSettings تعریف نشده است.");
                return;
            }

            logger.LogInformation(
                "MCP Seed: شروع Seed برای {Count} سرور ...",
                config.Servers.Count);

            foreach (var descriptor in config.Servers)
            {
                // اعتبارسنجی حداقلی
                if (descriptor.IsNullOrDefault() ||
                    descriptor.Name.IsNullOrEmpty())
                {
                    logger.LogWarning("MCP Seed: یک Descriptor نامعتبر نادیده گرفته شد.");
                    continue;
                }

                await SeedOneAsync(descriptor, cancellationToken);
            }

            logger.LogInformation("MCP Seed: عملیات به پایان رسید.");
        }

        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;

        // ────────────────────────────────────────────────────────
        // Seed یک Descriptor
        // ────────────────────────────────────────────────────────
        private async Task SeedOneAsync(
            XMcpServerDescriptor descriptor,
            CancellationToken cancellationToken)
        {
            try
            {
                var ownerId = config.DefaultOwnerId.IsNullOrEmpty()
                    ? "system"
                    : config.DefaultOwnerId;

                // بررسی وجود سرور با این نام و Owner
                var existing = await repositoryService.FindByNameAsync(
                    ownerId: ownerId,
                    name: descriptor.Name,
                    cancellationToken: cancellationToken
                );

                // ── حالت ایجاد ──
                if (existing.IsNullOrDefault())
                {
                    var item = MapToDto(descriptor, ownerId, id: null);
                    item.CreatedOn = DateTime.UtcNow;

                    await repositoryService.AddAsync(
                        item: item,
                        saveChanges: true,
                        cancellationToken: cancellationToken
                    );

                    logger.LogInformation(
                        "MCP Seed: سرور '{Name}' ایجاد شد.", descriptor.Name);
                    return;
                }

                // ── حالت به‌روزرسانی ──
                if (!config.UpdateExisting)
                {
                    logger.LogDebug(
                        "MCP Seed: سرور '{Name}' از قبل وجود دارد (UpdateExisting=false).",
                        descriptor.Name);
                    return;
                }

                var updateItem = MapToDto(descriptor, ownerId, id: existing.Id);
                updateItem.CreatedOn = existing.CreatedOn;
                updateItem.UpdatedAt = DateTime.UtcNow;

                await repositoryService.UpdateAsync(
                    item: updateItem,
                    id: existing.Id,
                    saveChanges: true,
                    cancellationToken: cancellationToken
                );

                logger.LogInformation(
                    "MCP Seed: سرور '{Name}' به‌روزرسانی شد.", descriptor.Name);
            }
            catch (Exception ex)
            {
                logger.LogError(ex,
                    "MCP Seed: خطا در Seed سرور '{Name}'. این سرور نادیده گرفته می‌شود.",
                    descriptor.Name);
            }
        }

        // ────────────────────────────────────────────────────────
        // تبدیل Descriptor به DTO
        // ────────────────────────────────────────────────────────
        private static XAiMcpServerDto MapToDto(
            XMcpServerDescriptor d,
            string ownerId,
            Guid? id)
        {
            var item = new XAiMcpServerDto
            {
                OwnerId = ownerId,
                Name = d.Name,
                Description = d.Description,
                Enabled = d.Enabled,
                Transport = d.Transport,
                Command = d.Command,
                Endpoint = d.Endpoint,
                TimeoutSeconds = d.TimeoutSeconds,
                WorkingDirectory = d.WorkingDirectory,

                // تبدیل لیست/دیکشنری به JSON برای ذخیره در DB
                Arguments = d.Arguments.HasChild()
                    ? JsonSerializer.Serialize(d.Arguments)
                    : null,
                EnvironmentVariables = d.EnvironmentVariables.HasChild()
                    ? JsonSerializer.Serialize(d.EnvironmentVariables)
                    : null,
                Headers = d.Headers.HasChild()
                    ? JsonSerializer.Serialize(d.Headers)
                    : null,
            };

            if (id.HasValue) item.Id = id.Value;

            return item;
        }
    }
}
✓ رفتار Seeder:
  • اگر سروری در DB نیست → ایجاد می‌شود
  • اگر هست و UpdateExisting = false → دست نمی‌خورد
  • اگر هست و UpdateExisting = true → فیلدها به‌روزرسانی می‌شوند
  • خطای یک سرور باعث توقف کل فرآیند نمی‌شود
۹

ثبت در Startup.cs

Startup.cs (MODIFY)
// ── در ConfigureServices، بعد از AddXAiServices ──

// ۱. ثبت XMcpServersConfiguration از appSettings
services.Configure<XMcpServersConfiguration>(
    Configuration.GetSection("McpServers"));

// ۲. ثبت Seeder به‌صورت HostedService
services.AddHostedService<XMcpServerSeederService>();

// ۳. ثبت Connection Manager (از مرحله قبل)
services.AddSingleton<XMcpServerConnectionManager>();

// ۴. ثبت Health Monitor
services.AddHostedService<XMcpHealthMonitorService>();
⚠️ ترتیب اجرا: Seeder به‌عنوان IHostedService پس از ساخت کامل DI Container اجرا می‌شود، بنابراین به IXAiMcpServerRepositoryService دسترسی کامل دارد. این ترتیب تضمین می‌کند که تمام ثبت‌های ماژول xAiModels پیش از اجرای Seeder کامل شده باشند.
۱۰

کنترلر CRUD برای مدیریت از طریق API

Controllers/McpServersController.cs
xAiApi/Controllers/McpServersController.cs
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using xAiApi.Services;
using xCommons.Providers;
using xCommons.Extensions;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using xIdentityService.Controllers;
using xAiModels.Interfaces.Dtos;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

namespace xAiApi.Controllers
{
    [Authorize]
    [Route("[controller]")]
    public class McpServersController : XBaseIdentityApiV1Controller
    {
        private readonly IXAiMcpServerRepositoryService repositoryService;
        private readonly XMcpServerConnectionManager connectionManager;

        public McpServersController(
            ILogger<McpServersController> logger,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XValidationProvider validationProvider,
            XMcpServerConnectionManager connectionManager,
            IXAiMcpServerRepositoryService repositoryService
        ) : base(logger, appConfiguration, identityProvider, validationProvider)
        {
            this.connectionManager = connectionManager;
            this.repositoryService = repositoryService;
        }

        #region Loaders ...
        /// <summary>
        /// لیست تمام سرورهای MCP متعلق به کاربر جاری ...
        /// </summary>
        [HttpGet("")]
        public async Task<ActionResult<IEnumerable<XAiMcpServerDto>>> LoadAll(
            CancellationToken cancellationToken = default)
        {
            try
            {
                var userInfo = await GetUserInfo();

                var result = await repositoryService.FindManyAsync(
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken,
                    predicate: x => x.OwnerId == userInfo.UserId,
                    orderBuilder: x => x.OrderBy(y => y.Name)
                );

                return Ok(result);
            }
            catch (Exception ex)
            {
                return GetExceptionActionResult(ex);
            }
        }

        /// <summary>
        /// دریافت یک سرور بر اساس Id ...
        /// </summary>
        [HttpGet("{id:guid}")]
        public async Task<ActionResult<XAiMcpServerDto>> GetById(
            Guid id,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var userInfo = await GetUserInfo();

                var item = await repositoryService.GetAsync(
                    id: id,
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken
                );

                if (item.IsNullOrDefault() || item.OwnerId != userInfo.UserId)
                    XException.NotFound.Throw();

                return Ok(item);
            }
            catch (Exception ex)
            {
                return GetExceptionActionResult(ex);
            }
        }
        #endregion

        #region Creators ...
        /// <summary>
        /// ایجاد سرور MCP جدید ...
        /// </summary>
        [HttpPost("")]
        public async Task<ActionResult<XAiMcpServerDto>> Create(
            [FromBody] XAiMcpServerDto item,
            CancellationToken cancellationToken = default)
        {
            try
            {
                if (item.IsNullOrDefault() || item.Name.IsNullOrEmpty())
                    XException.InvalidArgs.Throw();

                var userInfo = await GetUserInfo();

                // بررسی یکتایی نام برای این Owner
                var existing = await repositoryService.FindByNameAsync(
                    ownerId: userInfo.UserId,
                    name: item.Name,
                    cancellationToken: cancellationToken
                );

                if (!existing.IsNullOrDefault())
                    XException.InvalidArgs.Throw("این نام قبلاً استفاده شده است.");

                // پر کردن فیلدهای ضروری
                item.Id = Guid.Empty;  // اطمینان از اینکه Id جدید تولید می‌شود
                item.OwnerId = userInfo.UserId;
                item.CreatedOn = DateTime.UtcNow;
                item.UpdatedAt = DateTime.UtcNow;

                var result = await repositoryService.AddAsync(
                    item: item,
                    saveChanges: true,
                    cancellationToken: cancellationToken
                );

                // بازسازی اتصال‌ها
                await connectionManager.RefreshAsync();

                return Ok(result);
            }
            catch (Exception ex)
            {
                return GetExceptionActionResult(ex);
            }
        }
        #endregion

        #region Updaters ...
        /// <summary>
        /// به‌روزرسانی سرور MCP ...
        /// </summary>
        [HttpPut("{id:guid}")]
        public async Task<ActionResult<XAiMcpServerDto>> Update(
            Guid id,
            [FromBody] XAiMcpServerDto item,
            CancellationToken cancellationToken = default)
        {
            try
            {
                if (item.IsNullOrDefault() || id == Guid.Empty)
                    XException.InvalidArgs.Throw();

                var userInfo = await GetUserInfo();

                var existing = await repositoryService.GetAsync(
                    id: id,
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken
                );

                if (existing.IsNullOrDefault() || existing.OwnerId != userInfo.UserId)
                    XException.NotFound.Throw();

                // پر کردن فیلدهای سیستم
                item.Id = id;
                item.OwnerId = existing.OwnerId;
                item.CreatedOn = existing.CreatedOn;
                item.UpdatedAt = DateTime.UtcNow;

                var result = await repositoryService.UpdateAsync(
                    item: item,
                    id: id,
                    saveChanges: true,
                    cancellationToken: cancellationToken
                );

                // بازسازی اتصال‌ها
                await connectionManager.RefreshAsync();

                return Ok(result);
            }
            catch (Exception ex)
            {
                return GetExceptionActionResult(ex);
            }
        }
        #endregion

        #region Removers ...
        /// <summary>
        /// حذف نرم یک سرور MCP ...
        /// </summary>
        [HttpDelete("{id:guid}")]
        public async Task<ActionResult<bool>> Remove(
            Guid id,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var userInfo = await GetUserInfo();

                var existing = await repositoryService.GetAsync(
                    id: id,
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken
                );

                if (existing.IsNullOrDefault() || existing.OwnerId != userInfo.UserId)
                    XException.NotFound.Throw();

                await repositoryService.RemoveAsync(
                    id: id,
                    softDelete: true,
                    saveChanges: true,
                    cancellationToken: cancellationToken
                );

                // بازسازی اتصال‌ها
                await connectionManager.RefreshAsync();

                return Ok(true);
            }
            catch (Exception ex)
            {
                return GetExceptionActionResult(ex);
            }
        }
        #endregion

        #region Actions ...
        /// <summary>
        /// اعتبارسنجی و اتصال دستی به یک سرور ...
        /// </summary>
        [HttpPost("{id:guid}/Test")]
        public async Task<ActionResult<string>> Test(
            Guid id,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var userInfo = await GetUserInfo();

                var item = await repositoryService.GetAsync(
                    id: id,
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken
                );

                if (item.IsNullOrDefault() || item.OwnerId != userInfo.UserId)
                    XException.NotFound.Throw();

                var message = await connectionManager.TestServerAsync(
                    item, cancellationToken);

                return Ok(message);
            }
            catch (Exception ex)
            {
                return GetExceptionActionResult(ex);
            }
        }
        #endregion
    }
}
💡 مسیرهای API:
متدمسیرتوضیح
GET/McpServersلیست تمام سرورهای کاربر
GET/McpServers/{id}دریافت یک سرور
POST/McpServersایجاد سرور جدید
PUT/McpServers/{id}به‌روزرسانی
DELETE/McpServers/{id}حذف نرم
POST/McpServers/{id}/Testاعتبارسنجی و تست اتصال
۱۱

به‌روزرسانی XMcpServerConnectionManager

حالا از DB می‌خواند، نه از IOptionsMonitor

در نسخه قبل، Connection Manager مستقیماً از IOptionsMonitor<XMcpServersConfiguration> می‌خواند. اکنون باید از دیتابیس بخواند:

xAiApi/Services/XMcpServerConnectionManager.cs (MODIFY)
using System;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using xAiApi.Constants;
using xAiModels.Models.Dtos;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Client;
using xAiModels.Interfaces.Dtos;

namespace xAiApi.Services
{
    public class XMcpServerConnectionManager : IAsyncDisposable
    {
        private readonly ILogger<XMcpServerConnectionManager> logger;
        private readonly IXAiMcpServerRepositoryService repositoryService;
        private readonly Dictionary<Guid, McpClient> clients = new();
        private readonly Dictionary<Guid, IList<McpClientTool>> tools = new();
        private readonly SemaphoreSlim initLock = new(1, 1);
        private bool isInitialized = false;

        public XMcpServerConnectionManager(
            ILogger<XMcpServerConnectionManager> logger,
            IXAiMcpServerRepositoryService repositoryService)
        {
            this.logger = logger;
            this.repositoryService = repositoryService;
        }

        /// <summary>
        /// دریافت تمام ابزارهای موجود از سرورهای فعال ...
        /// </summary>
        public async Task<IList<McpClientTool>> GetAvailableToolsAsync(
            CancellationToken cancellationToken = default)
        {
            if (isInitialized)
                return tools.Values.SelectMany(t => t).ToList();

            await initLock.WaitAsync(cancellationToken);
            try
            {
                if (isInitialized)
                    return tools.Values.SelectMany(t => t).ToList();

                // ← خواندن از DB به‌جای IOptions
                var servers = await repositoryService.FindManyAsync(
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken,
                    predicate: x => x.Enabled
                );

                if (servers.HasChild())
                {
                    var tasks = servers.Select(s =>
                        ConnectAndValidateAsync(s, cancellationToken));
                    await Task.WhenAll(tasks);
                }

                isInitialized = true;
                return tools.Values.SelectMany(t => t).ToList();
            }
            finally
            {
                initLock.Release();
            }
        }

        /// <summary>
        /// تست دستی یک سرور خاص ...
        /// </summary>
        public async Task<string> TestServerAsync(
            XAiMcpServerDto server,
            CancellationToken cancellationToken)
        {
            try
            {
                using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds));

                var client = await CreateClientAsync(server, cts.Token);
                await client.PingAsync(cts.Token);
                var serverTools = await client.ListToolsAsync(cts.Token);

                var names = string.Join(", ", serverTools.Select(t => t.Name));
                return $"✓ سرور '{server.Name}' پاسخگو است. {serverTools.Count} ابزار: {names}";
            }
            catch (Exception ex)
            {
                return $"✗ خطا: {ex.Message}";
            }
        }

        // ────────────────────────────────────────────────────────
        private async Task ConnectAndValidateAsync(
            XAiMcpServerDto descriptor,
            CancellationToken cancellationToken)
        {
            try
            {
                using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds));

                var client = await CreateClientAsync(descriptor, cts.Token);
                await client.PingAsync(cts.Token);
                var serverTools = await client.ListToolsAsync(cts.Token);

                clients[descriptor.Id] = client;
                tools[descriptor.Id] = serverTools;

                logger.LogInformation(
                    "MCP '{Name}': {Count} ابزار کشف شد.",
                    descriptor.Name, serverTools.Count);
            }
            catch (Exception ex)
            {
                logger.LogWarning(ex,
                    "MCP '{Name}': اتصال برقرار نشد، نادیده گرفته شد.",
                    descriptor.Name);
            }
        }

        // ────────────────────────────────────────────────────────
        private static async Task<McpClient> CreateClientAsync(
            XAiMcpServerDto s,
            CancellationToken cancellationToken)
        {
            IClientTransport transport = s.Transport?.ToLowerInvariant() switch
            {
                "http" => new HttpClientTransport(new HttpClientTransportOptions
                {
                    Endpoint = new Uri(s.Endpoint!),
                    AdditionalHeaders = ParseJsonDict(s.Headers),
                    TransportMode = HttpTransportMode.AutoDetect
                }),
                _ => new StdioClientTransport(new StdioClientTransportOptions
                {
                    Command = s.Command ?? "dotnet",
                    Arguments = ParseJsonList(s.Arguments) ?? new List<string>(),
                    WorkingDirectory = s.WorkingDirectory,
                    EnvironmentVariables = ParseJsonDict(s.EnvironmentVariables)?
                        .ToDictionary(kv => kv.Key, kv => (string?)kv.Value),
                    Name = s.Name,
                    ShutdownTimeout = TimeSpan.FromSeconds(5)
                })
            };

            return await McpClient.CreateAsync(transport,
                cancellationToken: cancellationToken);
        }

        // ────────────────────────────────────────────────────────
        private static Dictionary<string, string> ParseJsonDict(string json)
            => json.IsNullOrEmpty() ? null
                : JsonSerializer.Deserialize<Dictionary<string, string>>(json);

        private static List<string> ParseJsonList(string json)
            => json.IsNullOrEmpty() ? null
                : JsonSerializer.Deserialize<List<string>>(json);

        // ────────────────────────────────────────────────────────
        public async Task RefreshAsync()
        {
            logger.LogInformation("MCP: بازسازی اتصال‌ها ...");

            foreach (var client in clients.Values)
            {
                try { await client.DisposeAsync(); } catch { }
            }
            clients.Clear();
            tools.Clear();

            isInitialized = false;
            await GetAvailableToolsAsync(CancellationToken.None);
        }

        public async ValueTask DisposeAsync()
        {
            foreach (var client in clients.Values)
            {
                try { await client.DisposeAsync(); } catch { }
            }
            initLock.Dispose();
        }
    }
}
✓ نتیجه: حالا مدیریت کامل سرورهای MCP از طریق API انجام می‌شود. با هر تغییر (ایجاد، به‌روزرسانی، حذف)، متد RefreshAsync() فراخوانی می‌شود و ابزارهای کش‌شده به‌روز می‌شوند. appSettings فقط منبع Seed اولیه است.
۱۲

نمونه کامل appsettings.json

appsettings.json (MODIFY)
{
  "AiApiConfiguration": {
    "Models": [ /* ... مدل‌های موجود ... */ ],
    "Prompts": [ /* ... پرامپت‌های موجود ... */ ]
  },

  "McpServers": {
    "SyncOnStartup": true,
    "UpdateExisting": false,
    "DefaultOwnerId": "system",
    "Servers": [
      {
        "Name": "xai-knowledge",
        "Description": "سرور MCP جستجو در پایگاه دانش",
        "Enabled": true,
        "Transport": "stdio",
        "Command": "dotnet",
        "Arguments": [ "xAiMcpServer.dll" ],
        "TimeoutSeconds": 20
      },
      {
        "Name": "remote-tools",
        "Description": "ابزارهای تیمی از راه دور",
        "Enabled": true,
        "Transport": "http",
        "Endpoint": "https://tools.example.com/mcp",
        "Headers": {
          "X-API-Key": "your-key"
        },
        "TimeoutSeconds": 30
      },
      {
        "Name": "file-processor",
        "Description": "پردازش فایل با معیارهای سفارشی",
        "Enabled": false,
        "Transport": "stdio",
        "Command": "node",
        "Arguments": [ "file-processor.js", "--port", "3000" ],
        "EnvironmentVariables": {
          "LOG_LEVEL": "info"
        },
        "TimeoutSeconds": 15
      }
    ]
  },

  "ConnectionStrings": { /* ... */ },
  "Logging": { /* ... */ }
}
۱۳

تست و اعتبارسنجی

Testing & Validation

جریان تست پیشنهادی:

  1. Migration: پس از اعمال Migration، جدول AiMcpServers را در دیتابیس بررسی کنید.
  2. اجرای اپلیکیشن: لاگ‌های Seeder را در Output مشاهده کنید — باید پیام‌هایی مانند "MCP Seed: سرور 'xai-knowledge' ایجاد شد." نمایش داده شود.
  3. بررسی DB: با یک Query ساده (یا از طریق SQL Server Management Studio) رکوردهای ایجاد شده را ببینید.
  4. تست API: با یک توکن معتبر، GET /McpServers را فراخوانی کنید و لیست سرورها را ببینید.
  5. تست ایجاد: یک سرور جدید با POST /McpServers بسازید.
  6. تست Connection: با POST /McpServers/{id}/Test اعتبارسنجی کنید.
  7. تست Function Calling: از /DefaultAi/AskText استفاده کنید و ببینید که LLM ابزارهای MCP را فراخوانی می‌کند یا خیر.
⚠️ نکات مهم:
  • اگر Seeder با خطا مواجه شد، بقیه سرورها نباید تحت تأثیر قرار گیرند — این در کد پیاده‌سازی شده است.
  • هنگام اجرای dotnet ef migrations add، اگر خطای "GraphType not found" دریافت کردید، مقادیر null را برای GraphQL types جایگزین کنید یا آن‌ها را بسازید.
  • در محیط توسعه، پیشنهاد می‌شود UpdateExisting = true باشد تا تغییرات appSettings سریع اعمال شوند.
  • در محیط عملیاتی، UpdateExisting = false باشد تا APIها بازنویسی نشوند.
۱۴

جمع‌بندی و چک‌لیست نهایی

Summary & Checklist

چک‌لیست فایل‌های جدید/تغییر یافته:

  • Entity، DTO و Descriptor در xAiModels/Models ایجاد شد
  • EntityConfiguration و EntityRegisterar اضافه شد
  • Constants جدید در XAiModelsConstants افزوده شد
  • تمام Interfaces (Entities/Dtos/Enrichers) ایجاد شد
  • Repositoryها (EF/Mongo/InMemory) + KeyGenerator + Events + Hub + Provider ساخته شد
  • RepositoryService، ServiceProvider، Enricher پیاده‌سازی شد
  • Helper (سه متد Descriptor) به XAiModelsHelper اضافه شد
  • ثبت در XDIHelperExtension انجام شد
  • Mapper Profile به‌روزرسانی شد
  • Registerar در XAiApiDbContext ثبت شد
  • Migration اجرا شد
  • XMcpServersConfiguration و XMcpServerSeederService ایجاد شد
  • XMcpServerConnectionManager برای خواندن از DB تغییر کرد
  • McpServersController با CRUD کامل اضافه شد
  • Startup.cs به‌روزرسانی شد (Configure + HostedServices)
  • appsettings.json با بخش McpServers تکمیل شد

🎯 نتیجه نهایی

با اجرای این مراحل، معماری شما به سطح بالاتری از پویایی و قابلیت مدیریت می‌رسد:

appSettings → Seeder → DB → API CRUD → Connection Manager → ChatOptions.Tools → LLM

سرورهای MCP کاملاً قابل مدیریت از طریق API هستند، از طریق appSettings به‌طور خودکار Seed می‌شوند، به‌صورت دوره‌ای Health Check می‌شوند، و ابزارهایشان به‌صورت داینامیک در دسترس مدل‌های زبانی قرار می‌گیرند — بدون نیاز به تغییر کد یا ری‌استارت.